import json
import os
import shutil

from datetime import datetime
from typing import List

import fitz
import oss2
from anthropic import BaseModel
from fastapi import APIRouter, Depends, UploadFile, File
from sqlalchemy.orm import Session

from database.config import get_db
from models.model import *
from models.base import *
from utils.deps import verify_token
from lagent.agents.img_understand import ocrResume
from lagent.agents.resume_beauty import resumeAnalyze


router = APIRouter()

# 获取项目根目录
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, "..", "..", ".."))

# 阿里云配置
accessKeyID = 'LTAI5tC1ZV6SDscoPQZr7QsY'
accessKeySecret = 'zByBtNvjtNBIKhzr7cBnKF4zhIWatg'
auth = oss2.Auth(accessKeyID, accessKeySecret)
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
bucketName = "spark-agent"
bucket = oss2.Bucket(auth, endpoint, bucketName, region=region)

# 上传简历
@router.post('/upload')
async def upload_resume(upload_file: UploadFile = File(...),
                        currentUser: dict = Depends(verify_token),  # 添加 token 验证
                        db: Session = Depends(get_db)):
    # 上传用户
    username = currentUser['username']

    filename_ext = os.path.splitext(upload_file.filename)[1] # 获取原始扩展名
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    resumeFilename = f"resume_{timestamp}{filename_ext}"
    # 构建保存路径
    save_dir = os.path.join(project_root, "uploadFile")
    os.makedirs(save_dir, exist_ok=True)
    resume_save_path = os.path.join(save_dir, resumeFilename)

    # 写入文件
    with open(resume_save_path, "wb") as buffer:
        shutil.copyfileobj(upload_file.file, buffer)

    oss_object_key = f"resume/{resumeFilename}"
    bucket.put_object_from_file(oss_object_key, resume_save_path)
    resume_ali_path = "https://spark-agent.oss-cn-hangzhou.aliyuncs.com/resume/" + resumeFilename

    # 提取简历图片
    filename = resumeFilename.rsplit(".", 1)[0]
    resume_img_path = os.path.join(project_root, "uploadFile", f"{filename}.png")  # 简历图片路径
    with fitz.open(resume_save_path) as pdfDoc:
        page = pdfDoc[0]  # 获取第一页
        mat = fitz.Matrix(3, 3).prerotate(0)  # 放大、旋转
        pix = page.get_pixmap(matrix=mat, alpha=False)
        pix.save(resume_img_path)  # 保存为PNG

    # 简历图片上传至阿里云
    oss_img_key = f"resume/{filename}.png"
    bucket.put_object_from_file(oss_img_key, resume_img_path)
    resume_img_url = f"https://spark-agent.oss-cn-hangzhou.aliyuncs.com/resume/{filename}.png"

    resume_id =  f"resume_{timestamp}"
    resume = db.query(Resume).filter(Resume.username == username).first()
    if resume is None:
        newResume = Resume(resume_id = resume_id, resume_url = resume_ali_path, username = username, resume_img = resume_img_url)
        db.add(newResume)
        db.commit()
        db.refresh(newResume)
    else:
        resume.resume_id = resume_id
        resume.resume_url = resume_ali_path
        db.commit()
        db.refresh(resume)



    res_data = {"resume_id": resume_id, "resume_url": resume_ali_path, "resume_img": resume_img_url}
    return Success(code = 200, msg = "success", res_data = res_data)

class resumeID(BaseModel):
    resume_id: str

# 简历识别
@router.post('/ocr')
async def ocr_resume(resume_Id: resumeID,
                     db: Session = Depends(get_db)):
    resume_id = resume_Id.resume_id
    resume = db.query(Resume).filter(Resume.resume_id == resume_id).first()
    print(resume)
    resumeURL = resume.resume_url
    resume_filename = resumeURL.split("/")[-1]
    filename = resume_filename.rsplit(".", 1)[0] # 简历名(不带扩展名)
    resume_path = os.path.join(project_root,"uploadFile" , resume_filename) # 简历本地路径
    image_path = os.path.join(project_root,"uploadFile" , f"{filename}.png") # 简历图片路径
    print(resume_path)

    # 将简历pdf第一页转换为图片
    with fitz.open(resume_path) as pdfDoc:
        page = pdfDoc[0]  # 获取第一页
        mat = fitz.Matrix(3, 3).prerotate(0)  # 放大、旋转
        pix = page.get_pixmap(matrix=mat, alpha=False)
        pix.save(image_path)  # 保存为PNG

    # 星火模型识别
    resume_content = ocrResume(image_path)
    print("-------------------------------------------")
    print(resume_content)

    # 简历内容存数据库
    resume.resume_content = resume_content
    db.commit()
    db.refresh(resume)
    # 转换为 Python 字典
    resume_content_dict = json.loads(resume_content)

    # # 简历图片上传至阿里云
    # oss_object_key = f"resume/{filename}.png"
    # bucket.put_object_from_file(oss_object_key, image_path)
    # oss_image_path = f"https://spark-agent.oss-cn-hangzhou.aliyuncs.com/resume/{filename}.png"
    #
    # resume_content_dict["resume_img"] = oss_image_path
    return Success(code = 200, msg = "success", res_data = resume_content_dict)

@router.get('/my')
async def my_resume(currentUser: dict = Depends(verify_token),
                    db: Session = Depends(get_db)):
    username = currentUser['username']
    resume = db.query(Resume).filter(Resume.username == username).first()

    if resume is not None:
        res_data = json.loads(resume.resume_content)
        res_data.update({
            "resume_id": resume.id,
            "resume_url": resume.resume_url,
            "resume_img": resume.resume_img
        })
        return Success(code = 200, msg = "success", res_data = res_data)
    else:
        return Fail()

# 简历优化建议，调用ai
@router.post('/ai_recommend')
async def ai_recommend(resume_Id: resumeID,
                       db: Session = Depends(get_db)):
    resume_id = resume_Id.resume_id
    resume = db.query(Resume).filter(Resume.resume_id == resume_id).first()
    resume_content = resume.resume_content # 简历内容
    advantage, disadvantage, advice = resumeAnalyze(resume_content)
    print(advantage, disadvantage, advice)
    res_data = {"advantage":advantage, "disadvantage":disadvantage, "advice":advice}
    return Success(code = 200, msg = "success", res_data = res_data)


class ProjectSchedule(BaseModel):
    from_: str  # 用 from_ 避免关键词冲突
    to: str
class ProjectExperience(BaseModel):
    project_name: str
    projcet_schedule: ProjectSchedule
    project_role: str
    project_contribution: str
class EducationExperience(BaseModel):
    school: str
    major: str = None
    study_time: str = None
    courses: str = None
    scholarship: str = None
    gpa: str = None
class TechnologyStack(BaseModel):
    main_stack: str
    appendix_stack: str
class BasicInfo(BaseModel):
    name: str
    age: int
    tel: str
    email: str
    intention_position: str = None
    intention_city: str = None
class ResumeRequest(BaseModel):
    resume_id: str
    basic_info: BasicInfo
    education_experience_list: List[EducationExperience]
    technology_stack: TechnologyStack
    project_expericenc_list: List[ProjectExperience]
    self_evaluation: str = None

# 简历编辑
@router.get('/edit')
async def edit_resume(resumeRequest: ResumeRequest,
                      currentUser: dict = Depends(verify_token),
                      db: Session = Depends(get_db)):
    username = currentUser['username']
    resume_id = resumeRequest.resume_id

    # 将整个 ResumeRequest 转换为 dict，然后转为 JSON 字符串
    resume_json_dict = resumeRequest.dict()
    resume_json_str = json.dumps(resume_json_dict, ensure_ascii=False)

    resume = db.query(Resume).filter(Resume.username == username).first()
    if resume is not None:
        resume.resume_content = resume_json_str
        db.commit()
        db.refresh(resume)
        return Success(code = 200, msg = "success", res_data = {})
    else:
        return Fail()

